package com.bigben.springbootshiro.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.session.SessionException;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.LogoutFilter;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig{


    //创建realm对象，需要自定义
    @Bean(name = "userReaml")
    public UserRealm userRealm(){
        return new UserRealm();
    }

    //defaultwebsecuritymanager
    @Bean(name = "defaultWebSecurityManager")
    public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("userReaml") UserRealm userRealm){
        DefaultWebSecurityManager securityManager=new DefaultWebSecurityManager();
        securityManager.setRealm(userRealm);
        return securityManager;
    }


    //shirofilterfactory
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean bean=new ShiroFilterFactoryBean();
        LogoutFilter logoutFilter = new LogoutFilter();
        //设置安全管理器
        bean.setSecurityManager(defaultWebSecurityManager);
        //添加shiro过滤器
        /*
        * anon:无需认证
        * authc：必须认证
        * user：必须有记住我
        * perm：拥有对某个资源的权限能访问
        * role：拥有角色权限
        * */
        Map<String,String> filterChainDefinitionMap=new LinkedHashMap<>();

        //简单的拦截操作
        //filterChainDefinitionMap.put("/add","anon");
        //filterChainDefinitionMap.put("/update","authc");
        //权限管理
        filterChainDefinitionMap.put("/add","perms[user:add]");
        filterChainDefinitionMap.put("/update","perms[user:update]");

        bean.setFilterChainDefinitionMap(filterChainDefinitionMap);

        //设置登陆页面
        bean.setLoginUrl("/toLogin");
        //设置未授权跳转页面
        bean.setUnauthorizedUrl("/Noauth");
        //注销
        filterChainDefinitionMap.put("/loginOut","logout");

        return bean;
    }

    //整合ShiroDialect:用来整合shiro和thymeleaf
    @Bean
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }










}
